/**
 * @author AdinZ
 * @date 2020/11/9 15:44
 */
import {ElNotification, ElMessage, ElMessageBox, ElLoading} from 'element-plus'
import axios from '@/utils/request'
import router from '@/router'
import store from "@/store";
import {parseTime} from '@/utils/index'

function message(msg, title) {
    if (!title) title = '提示'
    ElNotification({title: title, message: msg, type: 'success'})
}

function error(msg) {
    ElMessage({message: msg, type: 'error', dangerouslyUseHTMLString: true})
}

function confirm(msg) {
    return ElMessageBox.confirm(msg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString:true
    })
}


function request(option) {
    return new Promise((resolve, reject) => {
        let loadding = ElLoading.service({
            fullscreen: true,
            text: '网络请求中....'
        })
        axios(option)
            .then((res) => {
                if (loadding) {
                    loadding.close()
                    loadding = null
                }
                if (res.code == 200) {
                    resolve(res)
                } else if (res.code === 401) {
                    r('/login')
                    reject(res)
                } else if (res.code === 403 || res.code == 402) {
                    r('/401')
                    reject(res)
                } else {
                    error(res.message)
                    reject(res)
                }
            })
            .catch((e) => {
                if (loadding) {
                    loadding.close()
                    loadding = null
                }
                reject(e)
                error(e.message)
            })
    })
}

function go(url, params) {
    if (url && url.length > 0) {
        if (url.startsWith('http')) window.open(url)
        else router.push({path: url, query: params})
    }
}

function back(i) {
    if (!i) i = -1
    router.back(i)
}

function to(url, params) {
    go(url, params)
}

function r(url, params) {
    if (url && url.length > 0) {
        if (url.startsWith('http://') || url.startsWith('https://')) location.replace(url)
        else router.replace({path: url, query: params})
    }
}

function post(url, parame, data) {
    return request({
        url: url,
        method: 'post',
        params: parame,
        data
    })
}

function upload(url, file, params, progress) {
    let data = new FormData();
    data.append('file', file)
    return request({
        url: url,
        method: 'post',
        params: params,
        data,
        onUploadProgress: progress
    })
}

function postConfirm(msg, url, parame, data) {
    return new Promise((resolve, reject) => {
        confirm(msg)
            .then(() => {
                post(url, parame, data)
                    .then((res) => {
                        resolve(res)
                    })
                    .catch((e) => {
                        reject(e)
                    })
            })

    })
}

function get(url, params) {
    return request({
        url: url,
        method: 'get',
        params: params
    })
}

function put(url, params, data) {
    return request({
        url: url,
        method: 'put',
        params: params,
        data
    })
}

function deleteConfirm(url, parame) {
    return new Promise((resolve, reject) => {
        confirm('确定要删除吗？')
            .then(() => {
                deletes(url, parame)
                    .then((res) => {
                        resolve(res)
                    })
                    .catch((e) => {
                        reject(e)
                    })
            })
            .catch((e) => {
                reject(e)
            })
    })
}

function apiDelete(url, id, cb) {
    return new Promise((resolve, reject) => {
        deleteConfirm(url + 'delete', {id: id}).then(() => {
            if (cb) cb();
            resolve()
        }).catch(reject)
    });
}

function apiPost(url, data, cb) {
    return new Promise((resolve, reject) => {
        post(url + (data.id ? 'edit' : 'add'), {}, data).then(() => {
            if (cb) cb();
            resolve()
        }).catch(reject)
    });
}

function apiQuery(url, query, cb) {
    return new Promise((resolve, reject) => {
        post(url + 'query', {}, query).then((res) => {
            if (cb) cb(res);
            resolve(res)
        }).catch(reject)
    })
}


function deletes(url, params) {
    return request({
        url: url,
        method: 'delete',
        params: params
    })
}


/**
 * 菜单id
 * @param mid
 * @returns {boolean}
 */
function isMenu(mid) {
    let list = store.state.user.menus;
    if (!list) return false;
    return list.includes(mid);
}

/**
 * 坐标距离计算
 * @param local 我的坐标对象 {lng:0,lat:0}
 * @param target 目标坐标对象 {lng:0,lat0}
 */
function getDistance(local, target) {
    var radLat1 = local.lat * Math.PI / 180.0;
    var radLat2 = target.lat * Math.PI / 180.0;
    var a = radLat1 - radLat2;
    var b = local.lng * Math.PI / 180.0 - target.lng * Math.PI / 180.0;
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
        Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * 6378.137;// EARTH_RADIUS;
    s = Math.round(s * 10000) / 10000;

    s = s * 1000

    if (isNaN(s)) {
        return 0 + 'm';
    }
    if (s > 1000) {
        //    大于1000米时
        s = Math.floor(s / 1000 * 100) / 100;
        s = s + 'Km'
    } else {
        //    小于1000米直接返回
        s = s + 'm'
    }
    return s;
}

function download(data, fileName) {
    let blob;
    if (data instanceof Blob) {
        blob = data;
    } else blob = new Blob([data]);

    if ('download' in document.createElement('a')) {
        const link = document.createElement('a')//创建a标签
        link.download = fileName//a标签添加属性
        link.style.display = 'none'
        link.href = URL.createObjectURL(blob)
        document.body.appendChild(link)
        link.click()//执行下载
        URL.revokeObjectURL(link.href) //释放url
        document.body.removeChild(link)//释放标签

    } else {
        navigator.msSaveBlob(blob, fileName)
    }
}

export function deleteArray(items, index) {
    delete items[index]
    items = items.filter(e => e != undefined)
    return items;
}

export default {
    message,
    error,
    confirm,
    post,
    get,
    put,
    deletes,
    deleteConfirm,
    postConfirm,
    go,
    to,
    back,
    r,
    upload,
    parseTime,
    isMenu,
    getDistance,
    download,
    apiDelete,
    apiPost,
    apiQuery,
    deleteArray
}
